package com.bsh.controller.account;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bsh.api.ApiUtils;
import com.bsh.dto.AccountNoticeQryDto;
import com.bsh.dto.UserEditDto;
import com.bsh.dto.UserListQryDto;
import com.bsh.mybatis.dataView.UserAccountInfo;
import com.bsh.mybatis.model.AccountChangeAudit;
import com.bsh.mybatis.model.User;
import com.bsh.service.AccountChangeAuditService;
import com.bsh.service.AccountService;
import com.bsh.service.UserService;
import com.bsh.shiro.UserContext;
import com.bsh.utils.IpUtil;
import com.bsh.utils.PageTools;
import com.bsh.utils.Pager;
import com.bsh.utils.excel.ColumonCfg;
import com.bsh.utils.excel.ExcelExportor;

/**
 * 用户资金账户操作
 * 
 * @author Administrator
 *
 */
@Controller
public class AccountUserController {
	private static Logger log = LoggerFactory.getLogger(AccountUserController.class);

	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	private AccountService accountServ;
	@Autowired
	private UserService userServ;
	@Autowired
	private AccountChangeAuditService changeAuditServ;
	/**
	 * 设置查询默认时间范围
	 */
	private void setDefaultDateTimeRange(AccountNoticeQryDto dto,int days){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(ApiUtils.objIsEmpty(dto.getCreateTime())&&ApiUtils.objIsEmpty(dto.getCreateTime1())){
        	  Calendar cal=Calendar.getInstance();
    		  cal.setTime(new Date());	
    		  cal.add(Calendar.DAY_OF_MONTH,-days);
    		  dto.setCreateTime(sdf.format(cal.getTime()));
    		  dto.setCreateTime1(sdf.format(new Date()));
        }        
	}
	
	/**
	 * 账户列表
	 */
	@RequestMapping(value = "/account/list")
	public ModelAndView login(@ModelAttribute UserListQryDto dto) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/account/accountList");

		String pageStr = request.getParameter("pageIndex");
		Integer pageIndex = Integer.parseInt(StringUtils.isEmpty(pageStr) ? "1" : pageStr);

		String sizeStr = request.getParameter("pageSize");
		Integer pageSize = Integer.parseInt(StringUtils.isEmpty(sizeStr) ? "20" : sizeStr);

		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = accountServ.getPage(pager, dto);
		mv.addObject("list", list);
		mv.addObject("pager", pager);
		mv.addObject("dto", dto == null ? new UserEditDto() : dto);
		return mv;
	}

	/**
	 * 修改账户资金--初使化
	 */
	@RequestMapping(value = "/account/{id}")
	public ModelAndView editAccount(@PathVariable(value = "id") Integer userid) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/user/accountEdit");
		UserAccountInfo acc = accountServ.getUserAccountInfo(userid);
		User user = userServ.getUser(userid);
		mv.addObject("acc", acc);
		mv.addObject("user", user);
		return mv;
	}


	/**
	 * 修改账户资金--保存
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/account/save")
	public ModelAndView editAccountSave(@ModelAttribute UserAccountInfo dto) throws Exception {
		ModelAndView mv = editAccount(dto.getUserid());
		mv.addObject("dto", dto);
		User user = (User) mv.getModelMap().get("user");

		if (dto.getMoney()==null&& dto.getCloudMoney()==null) {
			String msg = PageTools.alert("修改账户", "请输入变动金额", 1000);
			mv.addObject("actionMsg", msg);
			return mv;
		}
		if (StringUtils.isEmpty(dto.getMemo())){
			String msg = PageTools.alert("修改账户", "请输入变动原因", 1000);
			mv.addObject("actionMsg", msg);
			return mv;
		}
		
		if (user.getIsMerchant() !=null && user.getIsMerchant() == 1) {
			if (dto.getCloudMoney()!=null && dto.getCloudMoney().compareTo(BigDecimal.ZERO)>0 &&StringUtils.isEmpty(dto.getCloudMoneyType())) {
				String msg = PageTools.alert("修改账户", "请选择商家加币类型", 1000);
				mv.addObject("actionMsg", msg);
				return mv;
			}
		}
		//jane 普通会员也选择类型。  新规则高级会员也可买商币
		if (user.getIsMerchant() ==null || user.getIsMerchant() != 1) {
			if (dto.getCloudMoney()!=null && dto.getCloudMoney().compareTo(BigDecimal.ZERO)>0 &&StringUtils.isEmpty(dto.getCloudMoneyType())) {
				String msg = PageTools.alert("修改账户", "请选择会员加币类型", 1000);
				mv.addObject("actionMsg", msg);
				return mv;
			}
		}

		String cloudMoneyType = request.getParameter("cloudMoneyType");
		String ip = IpUtil.getIpAddr(request);

		AccountChangeAudit row = new AccountChangeAudit();
		row.setAccountid(dto.getAccountId());
		row.setUserid(dto.getUserid());
		row.setSubmitter(UserContext.getLoginUser().getId());
		row.setSubmitterName(UserContext.getLoginUser().getLoginName());
		row.setMoney(dto.getMoney());
		row.setCloudMoney(dto.getCloudMoney());
		row.setMemo(dto.getMemo());
		row.setCloudmoneytype(cloudMoneyType);
		row.setSubmitterIp(ip);
		row.setCreateTime(new Date());
		row.setStatus((short)0);

		Integer res = changeAuditServ.submitChangeAsk(row);

		String msg = PageTools.alertCloseFraRefresh("修改账户", res > 0 ? "提交成功，请等待审核！" : "保存失败", 1000);
		mv.addObject("actionMsg", msg);
		return mv;
	}
	
	/**
	 * 账户变动最终审核--列表
	 */
	@RequestMapping(value = "/account/change/log")
	public ModelAndView changeLogList(@ModelAttribute AccountNoticeQryDto dto) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/account/changeLogList");

		String pageStr = request.getParameter("pageIndex");
		Integer pageIndex = Integer.parseInt(StringUtils.isEmpty(pageStr) ? "1" : pageStr);

		String sizeStr = request.getParameter("pageSize");
		Integer pageSize = Integer.parseInt(StringUtils.isEmpty(sizeStr) ? "10" : sizeStr);

		setDefaultDateTimeRange(dto,1);
		
		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = changeAuditServ.getPage(pager, dto);
		mv.addObject("list", list);
		mv.addObject("pager", pager);
		mv.addObject("dto", dto == null ? new UserEditDto() : dto);

		return mv;
	}
	
	/**
	 * 后台管理员充值记录列表--导出
	 * @return 
	 */
	@RequestMapping(value = "/account/export")
	public ModelAndView rechargeByAdminListExport(@ModelAttribute UserListQryDto dto) {
		ModelAndView mv = new ModelAndView();	
		List<Map<String, Object>> list = accountServ.getAccountListExport(dto);
		
		List<ColumonCfg> cfg=new ArrayList<>();
		cfg.add(new ColumonCfg("name","用户名",150));
		cfg.add(new ColumonCfg("real_name","真实姓名",100));
		cfg.add(new ColumonCfg("sex","性别",100));
		cfg.add(new ColumonCfg("money","现金",100));
		cfg.add(new ColumonCfg("cloud_money","商币",100));
		cfg.add(new ColumonCfg("pname","推荐人",150));
		cfg.add(new ColumonCfg("mobile","手机号",150));
		cfg.add(new ColumonCfg("level","会员级别",150));
		cfg.add(new ColumonCfg("ip","登录ip",200));
		cfg.add(new ColumonCfg("is_merchant","是否是商户",100));
		cfg.add(new ColumonCfg("create_time","注册时间",200));		
		cfg.add(new ColumonCfg("is_effect","状态",100));
		
		ExcelExportor.exportExcelByCfg("会员账户信息.xls", cfg, list);
		
		return null;
	}
}
